<?php

class Jf_Controller_Plugin_Fpc extends Jf_Controller_Plugin_Abstract {

    protected $_enableModules = array('catalog');

    protected $_pageCache = null;

    protected $_cacheKey = null;

    public function dispatchLoopStartup (Jf_Controller_Request_Abstract $request, Jf_Controller_Response_Abstract $response) {
        if ( ! in_array (strtolower ($request -> getModuleName ()), $this -> _enableModules) || $request -> isPost ()) {
            return null;
        }
        $this -> _cacheKey = base64_encode ($request -> getRequestUri ());
        if ($request -> isXmlHttpRequest ()) {
            $this -> _cacheKey .= '_ajax';
        }
        $data = Jf::cache () -> get ($this -> _cacheKey);
        if (false === $data) {
            Jf::cache () -> set ($this -> _cacheKey, null);
            $this -> _pageCache = false;
        } else {
            exit ($response -> setBody ($data));
        }
    }

    public function preDispatch (Jf_Controller_Request_Abstract $request, Jf_Controller_Response_Abstract $response) {
        if ( ! $request -> isXmlHttpRequest ()) {
            $layout = new Jf_Controller_Plugin_Layout ();
            $this -> getDispatcher () -> registerPlugin ($layout, 'layout');
        }
    }

    public function dispatchLoopShutdown (Jf_Controller_Request_Abstract $request, Jf_Controller_Response_Abstract $response) {
        if (false === $this -> _pageCache) {
            Jf::cache () -> set ($this -> _cacheKey, $response -> getBody ());
        }
    }

}
